

package com.hazelcast.internal.server.tcp;

import com.hazelcast.instance.impl.OutOfMemoryErrorDispatcher;
import com.hazelcast.internal.networking.Channel;
import com.hazelcast.internal.networking.ChannelErrorHandler;
import com.hazelcast.internal.server.ServerConnection;
import com.hazelcast.logging.ILogger;

import java.io.EOFException;

public class TcpServerConnectionChannelErrorHandler implements ChannelErrorHandler {

    private final ILogger logger;

    public TcpServerConnectionChannelErrorHandler(ILogger logger) {
        this.logger = logger;
    }

    @Override
    public void onError(Channel channel, Throwable error) {
        if (error instanceof OutOfMemoryError memoryError) {
            OutOfMemoryErrorDispatcher.onOutOfMemory(memoryError);
        }

        if (channel == null) {
            // todo: question is if logging is the best solution. If an exception happened without a channel, it is a pretty
            // big event and perhaps we should shutdown the whole HZ instance.
            logger.severe(error);
        } else {
            TcpServerConnection connection = (TcpServerConnection) channel.attributeMap().get(ServerConnection.class);
            if (connection != null) {
                String closeReason = (error instanceof EOFException) ? "Connection closed by the other side" : "Exception in " + connection + ", thread=" + Thread.currentThread().getName();
                connection.close(closeReason, error);
            } else {
                logger.warning("Channel error occurred", error);
            }
        }
    }
}
